const jwt = require('jsonwebtoken');
const config = require('../config');
const userService = require('../modules/user/user.service');

/**
 * JWT Authentication middleware
 */
const authMiddleware = async (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        error: {
          status: 401,
          message: 'Access token is required',
        },
      });
    }

    const token = authHeader.substring(7); // Remove 'Bearer ' prefix
    
    const decoded = jwt.verify(token, config.jwt.secret);
    
    // Check if user still exists
    const user = await userService.findById(decoded.userId);
    if (!user) {
      return res.status(401).json({
        error: {
          status: 401,
          message: 'User not found',
        },
      });
    }

    // Check if user is active
    if (user.status !== 'active') {
      return res.status(401).json({
        error: {
          status: 401,
          message: 'User account is not active',
        },
      });
    }

    req.user = user;
    next();
  } catch (error) {
    next(error);
  }
};

/**
 * Role-based authorization middleware
 */
const authorize = (...roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({
        error: {
          status: 401,
          message: 'Authentication required',
        },
      });
    }

    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        error: {
          status: 403,
          message: 'Insufficient permissions',
        },
      });
    }

    next();
  };
};

module.exports = {
  authMiddleware,
  authorize,
};